package com.ruoyi.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.enums.OrderStatusEnum;
import com.ruoyi.system.domain.Cash;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.service.CashService;
import com.ruoyi.system.service.CountService;
import com.ruoyi.system.service.OrderService;
import com.ruoyi.system.vo.OrderAgentCountVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class CountServiceImpl implements CountService {
    @Resource
    private OrderService orderService;
    @Resource
    private CashService cashService;

    @Override
    public Object count(Long merchantId, String role) {
        Long userId = merchantId;
        if (StrUtil.equals("admin", role)) {//管理员查询所有数据
            merchantId = null;
        }
        Date start = DateUtil.beginOfDay(new Date());
        Date end = new Date();
        Order order = new Order();
        order.setMerchantId(merchantId);
        OrderAgentCountVo thisDay = this.count(merchantId, start, end);
        OrderAgentCountVo yesterday = this.count(merchantId, DateUtil.offsetDay(start, -1), start);
        Cash cash = cashService.getByUserId(userId);

        Map<String, Object> map = new HashMap<>();
        map.put("thisDay", thisDay);
        map.put("yesterday", yesterday);
        map.put("earning", cash.getEarning());
        return map;
    }

    public OrderAgentCountVo count(Long merchantId, Date start, Date end) {
        OrderAgentCountVo orderAgentCountVo = new OrderAgentCountVo();
        Order order = new Order();
        order.setMerchantId(merchantId);
        PageDomain pageDomain = new PageDomain();
        pageDomain.setBeginTime(DateUtil.formatDateTime(DateUtil.beginOfDay(new Date())));
        pageDomain.setEndTime(DateUtil.now());
        //总单数
        int totalNum = orderService.countByDomain(order, start, end);
        //总金额
        BigDecimal todayAmount = orderService.sum("amount", order, start, end);
        order.setOrderStatus(OrderStatusEnum.success.getValue());
        //成功单数
        int finishNum = orderService.countByDomain(order, start, end);
        //成功金额
        BigDecimal finishAmount = orderService.sum("amount", order, start, end);
        orderAgentCountVo.setTotalAmount(todayAmount);
        orderAgentCountVo.setTotalNum(totalNum);
        orderAgentCountVo.setFinishNum(finishNum);
        orderAgentCountVo.setFinishAmount(finishAmount);

        return orderAgentCountVo;
    }



}
